<?php
class UsersController extends AppController {

	var $name = 'Users';
	var $components = array('Auth', 'Session', 'EmailSender');
	var $uses = array('User', 'ProfileParametr');
	
	function beforeFilter()
	{
		parent::beforeFilter();
		
		$this->Auth->allow('login', 'registration', 'forgot_password');
		$this->Auth->loginRedirect = '/';
		$this->Auth->autoRedirect = false;
		$this->Auth->userScope = array('User.status' => 'active');
		$this->Auth->loginError = "Login filed!";
	}
	
	function status($user_id = null, $status = null)
	{
		if ($this->Auth->user('role') != 'admin' || empty($user_id) || empty($status))
		{
			$this->redirect('/');
		}
		
		$this->User->recursive = -1;
		$user = $this->User->find('first', array('conditions' => array('User.id' => $user_id)));
		
		if (empty($user))
		{
			$this->redirect('/');
		}
		
		$user['User']['status'] = ($status == 'active') ? 'active' : 'inactive';
		
		if ($this->User->save($user))
		{
			if ($status == 'active')
			{
				$this->Session->setFlash(__('User <b>' . $user['User']['username'] . '</b> has been activated', true));
			}
			else
			{
				$this->Session->setFlash(__('User <b>' . $user['User']['username'] . '</b> has been inactivated', true));
			}
		}
		else
		{
			$this->Session->setFlash(__('Unexpected error', true));
		}
		
		$this->redirect('/users/control_users');
	}
	function generateRegistrationCode($user)
	{
		$codes = $this->User->find('list', array(
			'conditions' => array('registration_code IS NOT NULL'),
			'fields' => array('id', 'registration_code')
		));

		$code = '';
		do {
			$code = substr(md5($code.$user['User']['username'].$user['User']['email']) , 0, 5);
		}while(in_array($code, $codes));
		
		return $code;
	}
	
	function registration($code = null)
	{
		
		$this->layout = 'empty';
		
		$user = $this->Auth->user();
		if (!empty($user) || (empty($this->data) && empty($code)))
		{
			$this->redirect('/');
		}
		
		if ($this->data)
		{
			$user = $this->User->find('first', array('conditions' => array(
				'User.registration_code' => $this->data['User']['registration_code'],
				'User.id' => $this->data['User']['id']
			)));
			
			if (!empty($user) && $this->data['User']['password'] == $this->data['User']['password_confirm'])
			{
				$this->data['User']['registration_code'] = NULL;
				$this->data['User']['username'] = $user['User']['username'];
				$this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
				$this->data['User']['status'] = 'active';
				if ($this->User->save($this->data, array('fieldList' => array('registration_code', 'password', 'status', 'id'))))
				{
					$this->Auth->login($this->data);
					$this->redirect('/');
				}
			}
			else
			{
				$this->redirect('/');
			}
		}
		
		$this->User->recursive = -1;
		$user = $this->User->find('first', array('conditions' => array('User.registration_code' => $code)));
		if (empty($user))
		{
			$this->redirect('/');
		}
		
		$this->data = $user;
	}
	
	function login()
	{
		$this->layout = 'empty';
		
		$user = $this->Auth->user(); // Хренова магия, эта функция производит login
		if (!empty($user))
		{
			$this->redirect('/');
		}

		// таким образом этот код пусть будет на всякий случай
		if (!empty($this->data))
		{
			if($this->Auth->login($this->data))
			{
				$this->redirect('/');
			}
			else
			{
				$this->Session->setFlash(__('Login filed', true));
			}
		}
	}
	
	function logout()
	{
		$this->Auth->logout();
		$this->redirect('/users/login');
	}

	function control_users() {
		if ($this->Auth->user('role') != 'admin')
		{
			$this->redirect('/');
		}
		$this->User->recursive = 0;
		$this->set('users', $this->User->find('all'));
	}

	function add() {
		if (!empty($this->data)) {
			$this->User->create();
			$this->data['User']['registration_code'] = $this->generateRegistrationCode($this->data);
			$this->data['User']['status'] = 'inactive';
			if ($this->User->save($this->data, array('fieldList' => array('username', 'email', 'role', 'registration_code', 'status')))) {
				$this->EmailSender->registration($this->data);
				$this->ProfileParametr->save(array('ProfileParametr' => array('user_id' => $this->User->id, 'data' => serialize(array(
					'selected_user' => 'all',
					'selected_status' => 'all',
					'selected_project' => '',
				)))));
				$this->redirect(array('action' => 'control_users'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
		$projects = $this->User->Project->find('list');
		$this->set(compact('projects'));
	}
	
	function forgot_password()
	{
		$this->layout = 'empty';
		
		$user = $this->Auth->user();
		if (!empty($user))
		{
			$this->redirect('/');
		}
		
		if ($this->data)
		{
			$this->User->recursive = -1;
			$user = $this->User->find('first', array('conditions' => array(
				'User.username' => $this->data['User']['username'],
				'User.email' => $this->data['User']['email'],
				'User.status' => 'active'
			)));
			
			if (empty($user))
			{
				$this->Session->setFlash(__('Invalid username or email. Please, try again.', true));
			}
			else
			{
				$new_password = substr($user['User']['password'], 0, 5);
				$user['User']['password'] = $this->Auth->password($new_password);
				
				if ($this->User->save($user) && $this->EmailSender->password($user, $new_password))
				{
					$this->Session->setFlash(__('New password has been sended on your email address.', true));
					$this->redirect('/users/login');
				}
				
				$this->Session->setFlash(__('Unexpected error. Please, try again.', true));
			}
		}
	}
	
	function send_code($user_id)
	{
		if ($this->Auth->user('role') != 'admin' || empty($user_id))
		{
			$this->redirect('/');
		}
		
		$this->User->recursive = -1;
		$user = $this->User->find('first', array('conditions' => array(
			'User.id' => $user_id,
			'User.status' => 'inactive',
			'User.registration_code <>' => null
		)));
		
		if (empty($user))
		{
			$this->redirect('/');
		}
		
		if ($this->EmailSender->registration($user))
		{
			$this->Session->setFlash('Code has been sended');
		}
		else
		{
			$this->Session->setFlash('Error! Please, try again');
		}
		
		$this->redirect('/users/control_users');
		
	}
	
	function profile()
	{
		if (!empty($this->data))
		{
			$user = $this->User->find('first', array('conditions' => array(
				'User.id' => $this->Auth->user('id'),
				'User.password' => $this->Auth->password($this->data['User']['old_password'])
			)));
			
			if (!empty($user))
			{
				$this->data['User']['new_password'] = trim($this->data['User']['new_password']);
				if (!empty($this->data['User']['new_password']) && $this->data['User']['new_password'] == $this->data['User']['confirm_password'])
				{
					$this->User->save(
						array('User' => array(
							'id' => $this->Auth->user('id'),
							'password' => $this->Auth->Password($this->data['User']['new_password'])
						)),
						array(
							'fieldList' => array('id', 'password')
						)
					);
					$this->Session->setFlash('Password has been modified');
					$this->redirect('/');
				}
				else
				{
					$this->Session->setFlash('Passwords not match');
				}
			}
			else
			{
				$this->Session->setFlash('Invalid old password');
			}
		
		}
	}
}
